﻿using System;
using System.Web.UI;
using Pantry.Business;
using Pantry.Commons;
using Pantry.Entity;
using System.Globalization;

namespace Pantry.Web.Users.Controls
{
    public partial class CreateDirectorate : UserControl
    {
        #region Private members
        private readonly IFormatProvider _formatProvider = CultureInfo.CurrentCulture;
        private CountyBus _countyBus;
        private CountryBus _countryBus;
        private Directorate _directorate;
        private DirectorateBus _directorateBus;
        private ContactBus _contactBus;
        private TypeOfBusinessBus _typeOfBusinessBus;
        private OrganizationBus _organizationBus;
        private Organization _organization;
        private string _mode = "";
        private int _id;
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            ViewState["AddressLine1Bak"] = TextBoxAddressLine1.Text;
            ListContact.SendContactToPage += delegate(string contact)
                                                 {
                                                     string[] contacts = contact.Split('$');
                                                     HiddenContactId.Value = contacts[0];
                                                     TextBoxLeadContactName.Text = contacts[1];
                                                 };
            ListPostCode.sendPostcodeToPage += delegate(string postcode)
                                                   {
                                                       string[] postcodes = postcode.Split('$');
                                                       TextBoxPostcode.Text = postcodes[0];
                                                       TextBoxTown.Text = postcodes[1];
                                                       TextBoxCounty.Text = postcodes[2];
                                                       DropDownCountry.SelectedValue = postcodes[3];
                                                   };
            ListBusiness.SendvaluesToThePage += delegate(string business)
                                                    {
                                                        string[] businesses = business.Split('$');
                                                        TextBoxTypeOfBusiness.Text = businesses[0];
                                                        HiddenFieldTypeOfBusiness.Value = businesses[1];
                                                    };
            if (!IsPostBack)
            {
                _mode = Request.QueryString["mode"];
                if (_mode == "create" && Request.QueryString["OrganizationId"] != null)
                {
                    BindToCountryList();
                    int organizationId = int.Parse(Request.QueryString["OrganizationId"], _formatProvider);
                    FillInitialData(organizationId);
                }
                else if (_mode == "edit" && Request.QueryString["id"] != null)
                {
                    try
                    {
                        BindToCountryList();
                        _id = int.Parse(Request.QueryString["id"], _formatProvider);
                        FillDetails(_id);
                    }
                    catch (FormatException exception)
                    {
                        ExceptionHandler.WriteErrorLog(exception);
                    }
                }
                else if (Request.RawUrl == "DirectorateDetails.aspx" && Request.QueryString["id"] != null)
                {
                    try
                    {
                        BindToCountryList();
                        _id = int.Parse(Request.QueryString["id"], _formatProvider);
                        FillDetails(_id);
                    }
                    catch (FormatException exception)
                    {
                        ExceptionHandler.WriteErrorLog(exception);
                    }
                }
            }
        }

        #region Support Methods
        /// <summary>
        /// Lay du lieu len khi load trang, trong truong hop la view details (edit)
        /// </summary>
        private void FillDetails(int directorateId)
        {
            try
            {
                _typeOfBusinessBus = new TypeOfBusinessBus();
                _directorateBus = new DirectorateBus();
                _contactBus = new ContactBus();
                _directorate = _directorateBus.GetDirectorateById(directorateId);
                //Do du lieu vao cac truong thong tin
                if (_directorate != null)
                {
                    HiddenDirectorateName.Value = _directorate.DirectorateName;
                    TextBoxDepartmentName.Text = _directorate.DirectorateName;
                    TextAreaShortDescriptionription.Text = _directorate.DirectorateShortDescription;
                    TextBoxLeadContactName.Text = _contactBus.ManagerNameById(_directorate.ContactId);
                    HiddenContactId.Value = _directorate.ContactId.ToString(_formatProvider);
                    TextBoxAddressLine1.Text = _directorate.AddressLine1;
                    TextBoxAddressLine2.Text = _directorate.AddressLine2;
                    TextBoxAddressLine3.Text = _directorate.AddressLine3;
                    TextBoxPostcode.Text = _directorate.Postcode;
                    TextBoxTown.Text = _directorate.Town;
                    TextBoxCounty.Text = _directorate.County;
                    DropDownCountry.SelectedValue = _countryBus.GetCountryIdByName(_directorate.Country).ToString(_formatProvider);
                    TextBoxTypeOfBusiness.Text =
                        (string)_typeOfBusinessBus.TypeOfBusinessById(_directorate.TypeOfBusinessId).Rows[0]["TypeName"];
                    HiddenFieldTypeOfBusiness.Value = _directorate.TypeOfBusinessId.ToString(_formatProvider);
                    TextBoxSicCode.Text = _directorate.SICcode;
                    TextAreaFullDescriptionription.Text = _directorate.DirectorateFullDescription;
                    TextBoxPhoneNumber.Text = _directorate.PhoneNumber;
                    TextBoxFax.Text = _directorate.Fax;
                    TextBoxEmail.Text = _directorate.Email;
                    TextBoxWebAddress.Text = _directorate.WebAddress;
                    TextBoxCharityNumber.Text = _directorate.CharityNumber;
                    TextBoxCompanyNumber.Text = _directorate.CompanyNumber;
                }
            }
            catch (ArgumentNullException exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
                Response.Write(exception.Message);
            }
        }
        /// <summary>
        /// Fills the initial data.
        /// </summary>
        /// <param name="organizationId">The Organization id.</param>
        private void FillInitialData(int organizationId)
        {
            try
            {
                _organization = new OrganizationBus().ReturnOrganizationById(organizationId);
                _typeOfBusinessBus = new TypeOfBusinessBus();
                //Fill data to fields
                HiddenFieldTypeOfBusiness.Value = 
                    _typeOfBusinessBus.TypeOfBusinessById(_organization.TypeOfBusinessId).Rows[0]["Id"].ToString();
                TextBoxSicCode.Text =
                    (string)_typeOfBusinessBus.TypeOfBusinessById(_organization.TypeOfBusinessId).Rows[0]["SiCcode"];
                TextBoxTypeOfBusiness.Text =
                    (string)_typeOfBusinessBus.TypeOfBusinessById(_organization.TypeOfBusinessId).Rows[0]["TypeName"];
                TextBoxWebAddress.Text = _organization.WebAddress;
            }
            catch (FormatException exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
        }
        /// <summary>
        /// Gan du lieu vao Dropdown Country.
        /// </summary>
        private void BindToCountryList()
        {
            try
            {
                _countryBus = new CountryBus();
                var dataTable = _countryBus.SelectAllCountry();
                DropDownCountry.DataValueField = "CountryId";
                DropDownCountry.DataTextField = "CountryName";
                DropDownCountry.DataSource = dataTable;
                DropDownCountry.DataBind();
            }
            catch (ArgumentNullException exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
        }
        #endregion

        #region Event Handlers
        /// <summary>
        /// Checks the box copy address checked changed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void CheckBoxCopyAddressCheckedChanged(object sender, EventArgs e)
        {
            if (CheckBoxCopyAddress.Checked)
            {
                //Lay OrganizationID
                if (Request.QueryString["OrganizationId"] != null)
                {
                    _organizationBus = new OrganizationBus();
                    int organizationId = int.Parse(Request.QueryString["OrganizationId"], _formatProvider);
                    _organization = _organizationBus.ReturnOrganizationById(organizationId);
                    TextBoxAddressLine1.Text = _organization.Address1;
                    TextBoxAddressLine2.Text = _organization.Address2;
                    TextBoxAddressLine3.Text = _organization.Address3;
                }
            }
            else
            {
                if (Request.QueryString["id"] != null)
                {
                    int id = int.Parse(Request.QueryString["id"], _formatProvider);
                    _directorateBus = new DirectorateBus();
                    _directorate = _directorateBus.GetDirectorateById(id);
                    TextBoxAddressLine1.Text = _directorate.AddressLine1;
                    TextBoxAddressLine2.Text = _directorate.AddressLine2;
                    TextBoxAddressLine3.Text = _directorate.AddressLine3;
                }
                else
                {
                    TextBoxAddressLine1.Text = string.Empty;
                    TextBoxAddressLine2.Text = string.Empty;
                    TextBoxAddressLine3.Text = string.Empty;
                }
            }
        }
        /// <summary>
        /// Buttons the save click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonSaveClick(object sender, EventArgs e)
        {

            try
            {
                if (Request.QueryString["OrganizationId"] != null)
                {
                    int organizationId = int.Parse(Request.QueryString["OrganizationId"], _formatProvider);
                    _mode = Request.QueryString["mode"];
                    _directorateBus = new DirectorateBus();
                    bool isExist = _directorateBus.CheckDirectorateNameIsExist(TextBoxDepartmentName.Text.Trim());
                    _directorate = new Directorate
                    {
                        DirectorateId = 1,
                        DirectorateName = TextBoxDepartmentName.Text,
                        DirectorateShortDescription = TextAreaShortDescriptionription.Text,
                        OrganizationId = organizationId,
                        ContactId = string.IsNullOrEmpty(HiddenContactId.Value) ? 0 : int.Parse(HiddenContactId.Value, _formatProvider), //Chua xu ly
                        AddressLine1 = TextBoxAddressLine1.Text,
                        AddressLine2 = TextBoxAddressLine2.Text,
                        AddressLine3 = TextBoxAddressLine3.Text,
                        Postcode = TextBoxPostcode.Text,
                        Town = TextBoxTown.Text,
                        County = TextBoxCounty.Text,
                        Country = DropDownCountry.SelectedItem.Text,
                        TypeOfBusinessId = int.Parse(HiddenFieldTypeOfBusiness.Value, _formatProvider),
                        SICcode = TextBoxSicCode.Text,
                        DirectorateFullDescription= TextAreaFullDescriptionription.Text,
                        PhoneNumber = TextBoxPhoneNumber.Text,
                        Email = TextBoxEmail.Text,
                        Fax = TextBoxFax.Text,
                        WebAddress = TextBoxWebAddress.Text,
                        CharityNumber = TextBoxCharityNumber.Text,
                        CompanyNumber = TextBoxCompanyNumber.Text,
                        IsActive = true
                    };
                    if (_mode == "edit" && Request.QueryString["id"] != null)
                    {
                        int directorateId = int.Parse(Request.QueryString["id"], _formatProvider);
                        if (HiddenDirectorateName.Value != TextBoxDepartmentName.Text)
                        {
                            if (!isExist)
                            {
                                _directorate.DirectorateId = directorateId;
                                bool result = _directorateBus.UpdateDirectorate(_directorate);
                                ScriptManager.RegisterStartupScript(UpdatePanel, GetType(), "MyKey",
                                                                           result
                                                                               ? "showmessage('Update directorate successfully !','SUCCESS','','false');"
                                                                               : "showmessage('Update directorate failed !','ERROR','','false');",
                                                                           true);
                            }
                            else
                            {
                                TextBoxDepartmentName.Focus();
                                ScriptManager.RegisterStartupScript(UpdatePanel, GetType(), "MyKey",
                                                                            "showmessage('Directorate Name is already exists !','ERROR','','false');",
                                                                            true);
                            }
                        }
                        else
                        {
                            _directorate.DirectorateId = directorateId;
                            bool result = _directorateBus.UpdateDirectorate(_directorate);
                            ScriptManager.RegisterStartupScript(UpdatePanel, GetType(), "MyKey",
                                                                       result
                                                                           ? "showmessage('Update directorate successfully !','SUCCESS','','false');"
                                                                           : "showmessage('Update directorate failed !','ERROR','','false');",
                                                                       true);
                        }
                    }
                    else
                    {
                        if (!isExist)
                        {
                            bool result = _directorateBus.CreateDirectorate(_directorate);
                            ScriptManager.RegisterStartupScript(UpdatePanel, GetType(), "MyKey",
                                                                        result
                                                                            ? "showmessage('Create new directorate successfully !','SUCCESS','','false');"
                                                                            : "showmessage('Cannot create new directorate !','ERROR','','false');",
                                                                        true);
                        }
                        else
                        {
                            TextBoxDepartmentName.Focus();
                            ScriptManager.RegisterStartupScript(UpdatePanel, GetType(), "MyKey",
                                                                        "showmessage('Directorate Name is already exists !','ERROR','','false');",
                                                                        true);
                        }
                    }
                }
            }
            catch (ArgumentNullException ex)
            {
                ExceptionHandler.WriteErrorLog(ex);
            }
        }
        /// <summary>
        /// Buttons the back click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonBackClick(object sender, EventArgs e)
        {
            int orgId = int.Parse(Request.QueryString["Organizationid"], _formatProvider);
            Response.Redirect("OrganizationDetails.aspx?id=" + orgId + "&action=update#table_wTabs-6");
        }
        /// <summary>
        /// Texts the box postcode text changed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void TextBoxPostcodeTextChanged(object sender, EventArgs e)
        {
            _countyBus = new CountyBus();
            bool result = _countyBus.CheckPostcodeValid(TextBoxPostcode.Text);
            if (!result)
            {
                TextBoxPostcode.Focus();
                TextBoxAddressLine1.Text = string.Empty;
                TextBoxAddressLine2.Text = string.Empty;
                TextBoxAddressLine3.Text = string.Empty;
            }
        }
        /// <summary>
        /// Buttons the in active click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonInactiveClick(object sender, EventArgs e)
        {
            if (Request.QueryString["id"] != null)
            {
                int directorateId = int.Parse(Request.QueryString["id"], _formatProvider);
                int orgId = int.Parse(Request.QueryString["OrganizationId"], _formatProvider);
                _directorateBus = new DirectorateBus();
                bool result = _directorateBus.InactiveDirectorate(directorateId);
                ScriptManager.RegisterStartupScript(UpdatePanel, GetType(), "MyKey",
                                                                        result
                                                                            ? "showmessage('This directorate has changed status to Inactive !','SUCCESS','','false');"
                                                                            : "showmessage('Cannot changed the status of this directorate !','ERROR','','false');",
                                                                        true);
                Response.Redirect("OrganizationDetails.aspx?id=" + orgId + "&action=update#table_wTabs-6");
            }
        }

        #endregion


    }
}